<template>
  <div class="shopbag">
    <div class="back-nav-box">
      <back-nav
        title="购物袋"
        left-text="返回"
        :right-text="edit ? '完成' : '编辑'"
        left-arrow
        @clickRight="clickRight"
        @navback="navback"
      ></back-nav>
    </div>
    <!-- 渲染购物车列表 -->
    <div class="shopbag-lists">
      <ul>
        <li v-for="item in shopbag" :key="item.sid">
          <div>
            <van-checkbox
              v-model="item.checked"
              @click="computTotal"
            ></van-checkbox>
          </div>
          <div class="product-pic"><img :src="item.small_img" /></div>
          <div class="product-msg">
            <div>
              <span class="zh-name">{{ item.name }}</span
              ><span class="pdType">{{ item.rule }}</span>
            </div>
            <div class="en-name">{{ item.enname }}</div>
            <div class="pdPrice">&yen;{{ item.price }}</div>
          </div>
          <!-- 步进器 -->
          <div class="stepper">
            <van-stepper
              :value="item.count"
              theme="round"
              button-size="22"
              disable-input
              @plus="changeShopbagCount(item.sid, ++item.count)"
              @minus="changeShopbagCount(item.sid, --item.count)"
            />
          </div>
        </li>
      </ul>
    </div>
    <!-- 提交订单 -->
    <div class="submitOrder">
      <div class="submitOrder-checkbox">
        <van-checkbox @click="checkAll" v-model="allcheck">全选</van-checkbox>
      </div>
      <div class="submitOrder-total">
        <span class="span1">合计:</span
        ><span class="span2">&yen;{{ totalPrice }}</span>
      </div>
      <div class="submitOrder-btn">
        <van-button
          round
          type="info"
          v-show="edit == false"
          @click="toOrderaccount"
          >提交订单</van-button
        >
        <van-button
          round
          type="info"
          :class="{ active: edit == true }"
          v-show="edit == true"
          @click="delBag"
          >删除</van-button
        >
      </div>
    </div>
    <!-- 占位 底部导航的 -->
    <div class="zanwei"></div>
  </div>
</template>
<script>
import BackNav from "../components/BackNav.vue";
export default {
  data() {
    return {
      shopbag: [],
      // checked:false,//复选框默认状态
      totalPrice: 0, //总金额
      edit: false, //编辑的状态
      allcheck: false,
      sidArr: [],
    };
  },
  components: { BackNav },
  created() {
    this.getShopBag();
    this.isLogin();

    // console.log(this.$route.params.sid!==undefined);
  },
  updated() {},
  methods: {
    // 验证是否已登录
    isLogin() {
      if (!sessionStorage.getItem("token")) {
        console.log('用户未登录');
        this.$router.push({ name: "Login" });
      }
    },
    // 跳转订单结算页
    toOrderaccount() {
      // 通过checked遍历出勾选的商品，将它们sid做成数组
      let arr = this.shopbag.filter((v) => {
        return v.checked == true;
      });
      console.log(arr);
      if (arr.length < 1) {
        this.$toast("请先勾选商品");
        return;
      }
      // let sidArr=[];
      arr.forEach((v) => {
        this.sidArr.push(v.sid);
      });
      console.log(this.sidArr);

      this.$router.push({
        name: "Orderaccount",
        params: { sidArr: this.sidArr },
      });
    },
    // nav返回键
    navback() {
      this.$router.go(-1);
    },
    // 删除按钮
    delBag() {
      let delArr = [];
      this.shopbag.forEach((v) => {
        if (v.checked) {
          delArr.push(v.sid);
        }
      });
      console.log("delArr", delArr);
      this.axios
        .post("/deleteShopcart", { sids: JSON.stringify(delArr) })
        .then((res) => {
          console.log("delBag=>res", res);
          if (res.data.code === 7000) {
            setTimeout(() => {
              this.getShopBag(); //删除之后重新渲染购物车
            }, 1000);
          }
        })
        .catch((err) => {
          console.log("delBag=>err", err);
        });

    },
    // 全选按钮  ------------------------------------------
    checkAll() {
      console.log(this.allcheck);
      this.shopbag.forEach((v) => {
        if (v.checked == false) {
          v.checked = true;
        } else if (v.checked == true) {
          v.checked = false;
        } else {
          v.checked = true;
        }
      });
      this.computTotal();
    },
    // 计算总价方法
    computTotal() {
      // 先判断有没有全选
      console.log("computTotal方法被调用");
      let i = "";
      console.log(" this.shopbag", this.shopbag);
      this.shopbag.every((v) => {
        i = v.checked == true;
        return i;
      });
      console.log(i);
      if (i == true) {
        this.allcheck = true;
      } else {
        this.allcheck = false;
      }
      // 计算金额
      this.totalPrice = 0;
      console.log("shopbag", this.shopbag);
      // 判断checked为true时，计算金额
      this.shopbag.forEach((v) => {
        // console.log(v.checked);
        let total = 0;
        if (v.checked == true) {
          console.log(1);
          total = v.count * v.price;
        }
        this.totalPrice += total;
        total = 0;
      });
      console.log("总价", this.totalPrice);
    },
    clickRight() {
      this.edit = !this.edit;
      if (this.edit == false) {
      }
    },
    // 获取购物车商品
    getShopBag() {
      this.axios({
        method: "get",
        url: "/findAllShopcart",
      })
        .then((res) => {
          console.log("getShopBag=>res", res);
          if (res.data.code === 5000) {
            res.data.result.forEach((v) => {
              v.checked = false;
            });
            this.shopbag = res.data.result;
            console.log("this.shopbag", this.shopbag);
            this.computTotal(); //重新计算总价
            // this.$route.params.sid!==undefined为true，说明是点击‘立即购买‘按钮过来的
            // console.log('sid',this.$route.params.sid);
            if (this.$route.params.sid !== undefined) {
              console.log(this.shopbag);
              this.shopbag.forEach((v) => {
                if (v.sid == this.$route.params.sid) {
                  console.log("v", v);
                  console.log("v.sid", v.sid);
                  v.checked = true;
                  this.toOrderaccount();
                }
              });
            }
          }
        })
        .catch((err) => {
          console.log("getShopBag=>err", err);
        });
    },
    // 修改购物车商品数量
    changeShopbagCount(sid, count) {
      // 调用计算总价方法
      // this.computTotal();
      //   console.log(sid,count);
      //    this.axios({
      //   method:'post',
      //   url:'/modifyShopcartCount',
      //   data:{
      //     sid,
      //     count
      //   }
      // }).then(res=>{
      //   console.log('modifyShopcartCount=>res',res);
      // }).catch(err=>{
      //   console.log('modifyShopcartCount=>err',err);
      // })

      this.axios
        .post("/modifyShopcartCount", { sid, count })
        .then((res) => {
          // console.log(count);
          console.log("modifyShopcartCount=>res", res);
        })
        .catch((err) => {
          console.log("err", err);
        });
    },
  },
};
</script>
<style lang="less" scoped>
.submitOrder-total .span1 {
  font-size: 14px;
}
.submitOrder-total .span2 {
  font-size: 16px;
  color: #0c34ba;
  margin-left: 5px;
}
//提交订单
.submitOrder {
  height: 50px;
  background-color: #fff;
  border-bottom: 1px solid rgb(221, 220, 220);
  position: sticky;
  bottom: 50px;
  display: flex;
  padding: 10px;
  box-sizing: border-box;
  align-items: center;
  .submitOrder-checkbox {
    flex: 1;
    font-size: 14px;
  }
  .submitOrder-total {
    flex: 1;
  }

  .submitOrder-btn {
    flex: 1;
    width: 110px;
    .van-button--info {
      width: 110px;
      background-color: #0c34ba;
      color: #f7f9fd;
      &.active {
        background-color: #ec132d;
      }
    }
  }
}
.zanwei {
  width: 100%;
  height: 50px;
}
.zh-name {
  font-size: 16px;
  // font-weight: bold;
  color: #666;
}
.en-name {
  font-size: 14px;
  color: #999;
  margin-top: 5px;
}
.pdType {
  font-size: 14px;
  margin-left: 10px;
  color: #999;
}
.pdPrice {
  font-size: 14px;
  margin-left: 10px;
  font-weight: bold;
  margin: 10px 0;
  color: #0c34ba;
}
// 渲染购物车列表
.shopbag-lists {
  width: 90%;
  min-height: 521px;
  margin: 0 auto;
  li {
    width: 100%;
    height: 100px;
    margin: 0 auto;
    margin-bottom: 10px;
    background-color: #fff;
    display: flex;
    align-items: center;
    padding: 10px;
    box-sizing: border-box;
    position: relative;
    // 步进器
    .stepper {
      position: absolute;
      right: 10px;
      bottom: 10px;
    }
    & div:first-child {
      flex: 1;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    .product-pic {
      flex: 3;
      margin-right: 10px;
      img {
        width: 100%;
      }
    }
    .product-msg {
      flex: 8;
    }
  }
}
.back-nav-box {
  z-index: 9;
  position: sticky;
  top: 0;
}
.shopbag {
  background-color: #f7f7f7;
  min-height: 100vh;
}
// 修改步进器颜色
/deep/.van-stepper--round .van-stepper__plus {
  background-color: #0c34ba;
}
/deep/.van-stepper--round .van-stepper__minus {
  color: #0c34ba;
  border-color: #0c34ba;
}
</style>
